# -*- encoding: utf-8 -*-
import json
import inspect
from Common.mysql import app
from flask import jsonify, request
from src.User.token import token_verify, token_user_id, before_request
from Common.yaml_method import YamlMethod
from src.ApiTest.SqlData.Function.add_sql import AddSql
from src.ApiTest.SqlData.Function.sql_list import SqlList
from src.ApiTest.SqlData.Function.update_sql import UpdateSql
from src.ApiTest.SqlData.Function.delete_sql import DeleteSQL
from src.ApiTest.Core.operational_db import OperationalDB
from src.ApiTest.Core.operational_function import OperationalFunction
from src.ApiTest.Core.operational_sql import OperationalSql

code = YamlMethod().read_data('code.yaml')['code']


@app.route('/sql/add', methods=['POST'])
@token_verify
def add_sql(create_user):
    """
    添加SQL配置接口
    :param create_user:
    :return:
    """
    data = json.loads(str(request.data, 'utf-8'))
    config_name = data['configName']
    project_data = data['projectName']
    if '/' in project_data:
        project_data = data['projectName'].split('/')
        project_name = project_data[0]
        project_id = project_data[1]
    else:
        project_name = project_data
        project_id = data['projectId']
    database_type = data['databaseType']
    function_name = data['functionName']
    sql_data = data['sqlData']
    pre_parameter = data['pre_parameter']
    after_parameter = data['after_parameter']

    # 校验参数
    if not all([config_name, project_id, project_name, database_type, function_name, sql_data, sql_data]):
        return jsonify(code=code[7], msg="信息不完整")

    # 提交信息
    res = AddSql().add_sql(config_name, project_id, project_name, database_type, function_name, sql_data, pre_parameter,
                           after_parameter, create_user)

    return jsonify(res)


@app.route('/sql/list', methods=['POST'])
@token_user_id
def sql_list(user_id):
    """
    获取SQL配置列表接口
    :return:
    """
    data = json.loads(str(request.data, 'utf-8'))
    page = data['page']
    limit = data['limit']
    config_name = data['configName']
    project_id = data['projectId']
    if '/' in str(project_id):
        project_id = project_id.split('/')[1]

    res = SqlList().sql_list(page, limit, user_id, config_name, project_id)
    return res


@app.route('/sql/update', methods=['POST'])
@token_verify
def sql_update(update_user):
    """
    更新SQL配置信息接口
    :param update_user: 操作用户名
    :return:
    """
    data = json.loads(str(request.data, 'utf-8'))
    print(data)
    config_id = data['id']
    config_name = data['configName']
    project_data = data['projectName']
    if '/' in project_data:
        project_data = data['projectName'].split('/')
        project_name = project_data[0]
        project_id = project_data[1]
    else:
        project_name = project_data
        project_id = data['projectId']
    database_type = data['databaseType']
    function_name = data['functionName']
    sql_data = data['sqlData']
    pre_parameter = data['pre_parameter']
    after_parameter = data['after_parameter']

    # 校验参数
    if not all([config_name, project_id, project_name, database_type, function_name, sql_data]):
        return jsonify(code=code[7], msg="信息不完整")

    res = UpdateSql().update_sql(config_id, config_name, project_id, project_name, database_type, function_name, sql_data,
                                 pre_parameter, after_parameter, update_user)
    return res


@app.route('/sql/delete', methods=['POST'])
@before_request
def sql_delete():
    """
    删除SQL配置信息接口
    :return:
    """
    data = json.loads(str(request.data, 'utf-8'))
    config_id = data['id']

    res = DeleteSQL().delete_sql(config_id)
    return res


@app.route('/sql/func', methods=['POST'])
@before_request
def func_list():
    """
    获取执行SQL方法函数名称接口
    :return:
    """

    function_names = []
    for name, member in inspect.getmembers(OperationalDB, inspect.isfunction):
        if not name.startswith("__"):  # 排除内置函数
            signature = inspect.signature(member)
            parameters = signature.parameters
            param_names = [param for param in parameters]
            param_names.remove('db_info')
            if 'self' in param_names:
                param_names.remove('self')
            if param_names:
                name = name + str(param_names)
            function_names.append(name)

    res = {
        'code': code[0],
        'data': function_names
    }

    return res


@app.route('/sql/run', methods=['POST'])
@before_request
def sql_run():
    """
    SQL语句调试接口
    :return:
    """
    data = json.loads(str(request.data, 'utf-8'))
    project_data = data['projectName']
    if '/' in project_data:
        project_data = data['projectName'].split('/')
        project_name = project_data[0]
    else:
        project_name = project_data
    environment = data['environment']
    func = data['functionName'].split('[')[0]
    sql_data = eval(data['sqlData'])
    db_type = data['databaseType']

    from src.ApiTest.ProjectConfig.MysqlInfo.mysqlinfo_list import MysqlList

    info = MysqlList().mysql_info(project_name, environment, db_type)
    db_info = dict(info['data']['mysqlInfo'])

    response = OperationalSql().operational_sql(db_info, func, sql_data)

    res = {
        'code': code[0],
        'message': str(response)
    }
    return res


